package org.zfes.snowier.zbss.xzy.oss;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.Bucket;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;

@Service
public class AliyunOssService {
	
	private Logger logger = LoggerFactory.getLogger(AliyunOssService.class);
	
	private  String endpoint = "http://oss-cn-beijing.aliyuncs.com";
    private  String accessKeyId = "LTAIHsUzwlidx9MC";
    private  String accessKeySecret = "zurkyY6bNWw74TJ3m2xaeYBiMmn7qU";
    private  String bucketName = "xzyzht";
    
    private OSSClient ossClient;
    
    
    public static void main(String[] args) throws FileNotFoundException {
    	AliyunOssService aliyunOssService=new AliyunOssService();
    	String key=aliyunOssService.upload(new FileInputStream(new File("D:\\a.jpg")), "a.jpg");
    	String url= aliyunOssService.getUrl("ac.jpg") ;
    	System.out.println("key:"+key);
    	System.out.println("key:"+url);
	}
    private OSSClient getOssClient() {
    	if(ossClient==null) {
    		ossClient = (OSSClient) new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    	}
    	return ossClient;
    }
  
    public String getUrl(String key) {
        // 设置URL过期时间为10年  3600l* 1000*24*365*10
        Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
        // 生成URL
        URL url = getOssClient().generatePresignedUrl(bucketName, key, expiration);
        if (url != null) {
            return url.toString();
        }
        return null;
    }

//	public String imgUrl(String key) {
//		Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
//       GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(bucketName, key, HttpMethod.GET);
//       URL signedUrl = getOssClient().generatePresignedUrl(req);
//       return signedUrl.toString();
//	}
	
	public String upload(InputStream instream, String fileName) {
//		  ObjectMetadata objectMetadata = new ObjectMetadata();
//          objectMetadata.setContentLength(instream.available());
//          objectMetadata.setCacheControl("no-cache");
//          objectMetadata.setHeader("Pragma", "no-cache");
//          objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
//          objectMetadata.setContentDisposition("inline;filename=" + fileName);

          
         PutObjectResult putResult = getOssClient().putObject(bucketName,  fileName, instream);
         String tag = putResult.getETag();
         
         System.out.println(tag);
         return tag;
         
        // GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(bucketName, fileName, HttpMethod.GET);
        // URL signedUrl = getOssClient().generatePresignedUrl(req);
         //System.out.println(signedUrl);
	}
	
	 public String upload(String bucketName,String folder){  
	        //文件夹名   
	        final String keySuffixWithSlash =folder;  
	        //判断文件夹是否存在，不存在则创建  
	        if(!ossClient.doesObjectExist(bucketName, keySuffixWithSlash)){  
	            //创建文件夹  
	            ossClient.putObject(bucketName, keySuffixWithSlash, new ByteArrayInputStream(new byte[0]));  
	            logger.info("创建文件夹成功");  
	            //得到文件夹名  
	            OSSObject object = ossClient.getObject(bucketName, keySuffixWithSlash);  
	            String fileDir=object.getKey();  
	            return fileDir;  
	        }  
	        return keySuffixWithSlash;  
	 } 
	 
	 public  String createBucket(OSSClient ossClient,String bucketName){  
	        //存储空间  
	        final String bucketNames=bucketName;  
	        if(!ossClient.doesBucketExist(bucketName)){  
	            //创建存储空间  
	            Bucket bucket=ossClient.createBucket(bucketName);  
	            logger.info("创建存储空间成功");  
	            return bucket.getName();  
	        }  
	        return bucketNames;  
	 }  
	 
	public   void deleteBucket(OSSClient ossClient, String bucketName){    
        ossClient.deleteBucket(bucketName);     
        logger.info("删除" + bucketName + "Bucket成功");    
    }

	public  void deleteFile(OSSClient ossClient, String bucketName, String folder, String key){      
	         ossClient.deleteObject(bucketName, folder + key);     
	         logger.info("删除" + bucketName + "下的文件" + folder + key + "成功");    
	 }   
	 public   String createFolder(OSSClient ossClient,String bucketName,String folder){  
	        //文件夹名   
	        final String keySuffixWithSlash =folder;  
	        //判断文件夹是否存在，不存在则创建  
	        if(!ossClient.doesObjectExist(bucketName, keySuffixWithSlash)){  
	            //创建文件夹  
	            ossClient.putObject(bucketName, keySuffixWithSlash, new ByteArrayInputStream(new byte[0]));  
	            logger.info("创建文件夹成功");  
	            //得到文件夹名  
	            OSSObject object = ossClient.getObject(bucketName, keySuffixWithSlash);  
	            String fileDir=object.getKey();  
	            return fileDir;  
	        }  
	        return keySuffixWithSlash;  
	 } 
	public void checkBucket() {
		  // 判断Bucket是否存在。详细请参看“SDK手册 > Java-SDK > 管理Bucket”。
        // 链接地址是：https://help.aliyun.com/document_detail/oss/sdk/java-sdk/manage_bucket.html?spm=5176.docoss/sdk/java-sdk/init
        if (ossClient.doesBucketExist(bucketName)) {
            System.out.println("您已经创建Bucket：" + bucketName + "。");
        } else {
            System.out.println("您的Bucket不存在，创建Bucket：" + bucketName + "。");
            // 创建Bucket。详细请参看“SDK手册 > Java-SDK > 管理Bucket”。
            // 链接地址是：https://help.aliyun.com/document_detail/oss/sdk/java-sdk/manage_bucket.html?spm=5176.docoss/sdk/java-sdk/init
            ossClient.createBucket(bucketName);
        }
	}
	

}
